const app = getApp();

Page({
  data: {
    user: {},
    todos:[]
  },
  // 页面初始化 
  onLoad() { 
    basement.function.invoke('getUserInfo').then((res) => { 
      if (res.success) { 
        this.setData({ user: res.result }); 
   // 更新页面的用户信息 
      } 
    }).catch(console.error); 
  },

  onShow() {
    // this.setData({ todos: app.todos });
    this.loadTodoList();
  },

  onTodoChanged(e) {
    if (this.deleting) {
      return;
    }

    const ids = e.detail.value;
    let changeTarget = null;
    for (const todo of this.data.todos) {
      if (todo.completed && !ids.includes(todo._id)) {
        changeTarget = {
          _id: todo._id,
          completed: false,
        }
      }
      if (!todo.completed && ids.includes(todo._id)) {
        changeTarget = {
          _id: todo._id,
          completed: true,
        }
      }
    }

    if (changeTarget) {
      this.changeComplate(changeTarget._id, changeTarget.completed).then(res => {
        if (res.success) {
          this.loadTodoList();
        }
      });
    }
  },

  deleteIcon(e) {
    this.deleting = true;
    this.deleteById(e.target.dataset.delete._id).then(res => {
      if (res.success) {
        this.loadTodoList();
      }
    });
  },
  addTodo() {
    my.navigateTo({ url: '../add-todo/add-todo' });
  },

  // 获得数据并加载当前用户 todo 列表
  loadTodoList(){
   
    basement.db.collection('todos').find(
      { userId: this.data.user.userId }, // 获取当前用户的 todo 记录
      { sort: { createTime: -1 } }, // 按时间倒序排列
    ).then(({ result: todos }) => {
      
      this.setData({ todos }); // 页面页面的 todo 列表
    }).catch(console.error);
  },
  // 根据 id 改变当前 todo 状态
  changeComplate(_id, completed){
    return new Promise(function (resolve, reject) {

      basement.db.collection('todos').updateOne(
        { _id }, // 更新的条件
        {
          $set: { // 更新 todo 的状态和最后完成时间
            completed,
            completeTime: completed ? new Date() : false,
          }
        }
      ).then(() => {
         
        resolve({ success: true });
      }).catch(err => {
      
        console.error(err);
        reject({ success: false });
      });

    });
  },
  // 删除当前的列表
  deleteById(_id){
    const that = this;
    return new Promise(function (resolve, reject) {
      
      // 确认和删除图片
      my.confirm({
        title: '删除记录',
        content: '是否确认删除?',
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        success: (result) => {
          if (result.confirm) {
            basement.db.collection('todos').deleteOne({ // 删除特定用户特定 _id 的 todo 项
              _id,
              userId: that.data.user.userId,
            }).then(() => {
              resolve({ success: true });
            }).catch(err => {
              console.error(err);
              reject({ success: false });
            });
          }
        },
      });

    });
  }
});
